<template>
  <view class="ass-info-picker">
    <view v-if="$slots.handler" @click="show=!show">
      <slot name="handler"></slot>
    </view>
    <view v-else class="ass-info-picker-handler" @click="show=!show">
      <text class="ass-info-picker-value"
        v-if="!multiple && value && value.length">{{value[0][defaultProps.name]}}</text>
      <text class="ass-info-picker-value"
        v-else-if="multiple && value && value.length==1">{{value[0][defaultProps.name]}}</text>
      <text class="ass-info-picker-value"
        v-else-if="multiple && value && value.length>1">{{value[0][defaultProps.name]}}<text
          class="color-gray"> 等{{value.length}}项</text></text>
      <text class="ass-info-picker-placeholder" v-else>{{placeholder}}</text>
      <text class="ass-info-picker-arrow iconfont icon-down-arrow-line"></text>
    </view>
    <u-popup :show="show" @close="show=false" @open="show=true">
      <view class="ass-info-picker__body">
        <view class="p10">
          <u-search v-model="searchKey" placeholder="输入关键词搜索" :showAction="false" @search="onSearch"></u-search>
        </view>
        <su-category-filter :treeData="treeData" v-model="categoryVal" :defaultProps="treedefaultProps"
          @change="changeHandler"></su-category-filter>
        <view class="ass-info-list__container">
          <view class="mt30 mb30 align-center" v-if="listLoading">
            <su-list-loading>加载中...</su-list-loading>
          </view>
          <ass-info-card pithy v-for="(item,index) in list" :key="index" :data="item">
            <template #left>
              <view class="ass-info-list__checkbox" @click.stop="checkOrCancelCheck(item)">
                <text class="iconfont icon-radio-checked ckeckbox-icon color-primary"
                  v-if="checkedIndex(item[defaultProps.id])!==-1"></text>
                <text class="iconfont icon-radio-notcheck ckeckbox-icon" v-else></text>
              </view>
            </template>
          </ass-info-card>
          <view class="ass-info-list__loadmore" v-if="!listLoaded && !listLoading" @click="listLoadHandler">
            点击加载更多
          </view>
        </view>
        <su-empty v-if="!list.length"></su-empty>
      </view>
      <view class="confirm-bottom" v-if="multiple">
        <view class="confirm-bottom-select-all" @click="checkAllHandler">
          <text class="iconfont icon-radio-checked ckeckbox-icon color-primary" v-if="checkedAll"></text>
          <text class="iconfont icon-radio-notcheck ckeckbox-icon color-gray" v-else></text>
          全选
        </view>
        <view class="confirm-bottom-count" @click="showResultList = true">
          已选择
          <text class="color-primary ml5 mr5 text-bold">{{checkedCount}}</text> 项
        </view>
        <view class="confirm-bottom-confirmbtn">
          <u-button type="primary" block @click="confirmHandler">确定</u-button>
        </view>
      </view>
      <!-- 选择结果 -->
      <u-popup :show="showResultList" @close="showResultList=false" @open="showResultList=true">
        <view class="result-list-header" v-if="tempCheckedList.length">
          <view>已选人员列表</view>
          <view class="clear-all-members" @click="clearupAll">
            <text class="iconfont icon-qingchu"></text> 清空
          </view>
        </view>
        <view class="ass-info-picker__popup-container">
          <view class="mt30" v-if="!tempCheckedList.length">
            <su-empty text="您啥也没有选～"></su-empty>
          </view>
          <ass-info-card v-if="tempCheckedList.length" pithy v-for="(item,index) in tempCheckedList" :key="index"
            :data="item">
            <template #left>
              <view class="ass-info-list__checkbox" @click.stop="checkOrCancelCheck(item)">
                <text class="iconfont icon-close-line delete-checked-icon"></text>
              </view>
            </template>
          </ass-info-card>

        </view>
      </u-popup>
    </u-popup>
  </view>
</template>

<script>
  /**
   * @description 资产选择
   * @date 2022-07-03
   * @version v1.0.1
   * @author xx
   */
  import {
    assettypetreeselect
  } from '@/common/api/mdm/mdmsort.js'
  import {
    assetionfoList
  } from '@/common/api/ass/assetinfo.js'
  import AssInfoCard from '@/pages/main/assetinfo/componts/ass-info-card2.vue'
  export default {
    name: "ass-info-picker",
    components: {
      AssInfoCard
    },
    model: {
      prop: 'value',
      event: 'change'
    },
    props: {
      value: {
        type: Array,
        default(){
          return []
        }
      },
      options: {
        type: Array,
        default () {
          return []
        }
      },
      multiple: {
        type: Boolean,
        default: false
      },
      defaultProps: {
        type: Object,
        default () {
          return {
            id: "id",
            name: "assetName",
            img: "assetPhoto",
          }
        }
      },
      placeholder: {
        type: [String, Number],
        default: '请选择'
      }
    },
    data() {
      return {
        show: false,
        innerVal: this.value,
        categoryVal: '',
        searchKey: '',
        treeData: [],
        treedefaultProps: {
          label: 'label',
          value: 'id',
          children: 'children'
        },
        pageIndex: 1,
        pageSize: 10,
        pageTotal: 0,
        list: [],
        listLoaded: false,
        listLoading: false,
        selectedNode: null,
        /////
        showResultList: false,
        checkedAll: false,
        disabledMembers: [], //需要禁用
        disabledToast: "",
        tempCheckedList: this.value || [], //选中的列表
      }
    },
    computed: {
      checkedCount() {
        return this.tempCheckedList.length;
      }
    },
    watch: {
      show(val) {
        this.$store.commit('setPopupOpen', val)
      }
    },
    mounted() {
      this.getCategoryTree()
      this.reloadList()
    },
    methods: {
      // 获取分类树
      getCategoryTree() {
        assettypetreeselect().then(res => {
          this.treeData = res.data || []
        })
      },
      //按关键字搜索
      onSearch() {
        this.reloadList()
      },
      changeHandler(item, level) {
        this.selectedNode = item
        this.reloadList()
      },
      reloadList() {
        this.list = []
        this.pageIndex = 1
        this.listLoaded = false
        this.listLoadHandler()
      },
      // 加载资产列表
      listLoadHandler() {
        if (this.listLoaded && this.listLoading) {
          return
        }
        this.listLoading = true
        assetionfoList({
          pageNum: this.pageIndex,
          pageSize: this.pageSize,
          assetName: this.searchKey,
          id: this.selectedNode ? this.selectedNode.id : '0',
        }).then(res => {
          this.listLoading = false
          this.list = res.rows || []
          this.pageTotal = res.total || 0
          if (this.list.length >= this.pageTotal) {
            this.listLoaded = true
          } else {
            this.pageIndex++
          }
        })
      },
      //////////////////
      //选择或取消选择操作
      checkOrCancelCheck(member) {
        if (this.disabledMembers.indexOf(member[this.defaultProps.id]) !== -1) {
          if (this.disabledToast) this.$toast(this.disabledToast);
          return;
        }
        let checkedIndex = this.checkedIndex(member[this.defaultProps.id]);
        if (!this.multiple) {
          //单选
          this.tempCheckedList = [member];
          this.confirmHandler();
          return;
        }
        if (checkedIndex !== -1) {
          //取消选中
          this.tempCheckedList.splice(checkedIndex, 1);
        } else {
          //选中
          this.tempCheckedList.push(member);
        }
        this.countCurrentCheckedMembers();
      },

      //查找某人是否被选中，并返回选中列表中的索引数
      checkedIndex(id) {
        for (var i in this.tempCheckedList) {
          if (this.tempCheckedList[i][this.defaultProps.id] === id) return i;
        }
        return -1;
      },

      //全选/全不选操作
      checkAllHandler() {
        this.checkedAll = !this.checkedAll
        let list = this.list;
        for (var i in list) {
          let member = list[i];
          if (this.disabledMembers.indexOf(member[this.defaultProps.id]) === -1) {
            let checkedIndex = this.checkedIndex(member[this.defaultProps.id]);
            //全不选
            if (!this.checkedAll && checkedIndex !== -1) {
              this.tempCheckedList.splice(checkedIndex, 1);
            }
            //全选
            if (this.checkedAll && checkedIndex === -1) {
              this.tempCheckedList.push(member);
            }
          }
        }
      },

      //比对当前页选中数量，如果等于当前页人员数量，则全选选中，否则全选取消选中
      countCurrentCheckedMembers() {
        if (!this.multiple) return;
        let list = this.list;
        this.checkedAll = list.every(
          item =>
          this.checkedIndex(item.MemberId) !== -1 ||
          this.disabledMembers.indexOf(item.MemberId) !== -1
        );
      },
      //确认选择结果
      confirmHandler() {
        const resList = this.tempCheckedList
        this.$emit('input', resList)
        this.$emit('change', resList)
        this.show = false
        this.showResultList = false
      },
      //清空所有选择
      clearupAll() {
        let tempArr = [];
        for (var i in this.tempCheckedList) {
          let item = this.tempCheckedList[i];
          if (this.disabledMembers.indexOf(item.MemberId) !== -1) {
            tempArr.push(item);
          }
        }
        if (tempArr.length) {
          this.$toast("有" + tempArr.length + "项不能清除");
        }
        this.tempCheckedList = tempArr;
        this.countCurrentCheckedMembers();
      },

    }
  }
</script>

<style lang="scss" scoped>
  .ass-info-picker {
    width: 100%;

    &__popup {
      &-container {
        height: 70vh;
        overflow: auto;
      }
    }

    &__body {
      height: 70vh;
      overflow: auto;
    }

    &-handler {
      display: flex;
      height: 100%;
      justify-content: space-between;
      align-items: center;
    }

    &-placeholder {
      font-size: 30upx;
      color: #bbb;
    }

    &-value {
      font-size: 30upx;
      color: #333;
    }

    &-arrow {
      color: #aaa;
      font-size: 28upx;
    }

    &-options {
      &-item {
        display: flex;
        align-items: center;
        font-size: 30upx;
        padding: 20upx 30upx;
        border-bottom: solid 1upx #f7f7f7;

        .iconfont {
          font-size: 48upx;
          color: #ddd;
        }

        &__start {
          flex: 1;
        }
      }
    }
  }

  .ass-info-list__container {
    padding: 20upx;
    background-color: #f7f7f7;
  }

  .ass-info-list__loadmore {
    color: $u-primary;
    font-size: 24upx;
    padding: 20upx;
    display: flex;
    justify-content: center;
    align-items: center;

    &:active {
      background-color: #fff;
    }
  }

  .confirm-bottom {
    margin-bottom: constant(safe-area-inset-bottom);
    margin-bottom: env(safe-area-inset-bottom);
    right: 0;
    display: flex;
    justify-content: space-between;
    padding-left: 30upx;
    background-color: #fff;
    z-index: 3;
    font-size: 28upx;
    box-shadow: 0 -12upx 40upx rgba(0, 0, 0, 0.07);

    &-count {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #999;

      text {
        text-decoration: underline;
        vertical-align: middle;
        margin-top: -2px;
      }
    }

    &-confirmbtn {
      flex: 1;

      .van-button {
        height: 100upx;
        border-radius: 0;
        font-weight: bold;
      }
    }

    &-select-all {
      display: flex;
      flex: 1;
      justify-content: flex-start;
      align-items: center;
      font-size: 28upx;

      .iconfont {
        font-size: 40upx;
        color: #aaa;
        margin-right: 10upx;
      }
    }
  }

  .result-list-header {
    height: 88upx;
    display: flex;
    padding: 0 30upx;
    justify-content: space-between;
    align-items: center;
    position: relative;
    font-size: 24upx;
    color: #666;

    .clear-all-members {
      color: $u-error;
    }

    i {
      font-size: 28upx;
      margin-right: 4upx;
    }

    border-bottom: solid 1upx #f7f7f7;
  }

  .delete-checked-icon {
    font-size: 20upx;
    width: 44upx;
    height: 44upx;
    color: #fff;
    background-color: rgba(0, 0, 0, 0.3);
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 44upx;
    padding-top: 2upx;
    box-sizing: border-box;
    color: #fff !important;
    font-size: 24upx !important;

    &:active {
      background-color: rgba(0, 0, 0, 1);
    }
  }
  .ass-info-list__checkbox{
    margin-left: -16upx;
    width: 88upx;
    height: 88upx;
    display: flex;
    justify-content: center;
    align-items: flex-start;
    margin-right:6upx;
    .iconfont{
      font-size: 48upx;
      color: #ddd;
    }
  }
</style>
